package com.zhentao.utils;

import com.zhentao.constants.Constants;
import com.zhentao.pojo.TUser;
import com.zhentao.redis.RedisCacheUtil;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class JwtService {

    // 设置token过期时间5小时
    private static final long EXPIRE_TIME = 5 * 60 * 60 * 1000; // 5小时
    // 加密KEY
    private static final String TOKEN_ENCRY_KEY = "MDk4ZjZi789y438h9jikoyg5ft4r9jigYyN2I0ZjY";

    @Resource
    private RedisCacheUtil redisCacheUtil;

    // 生产ID
    public static String createToken(Map<String, Object> claimMaps) {
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date(currentTime)) // 签发时间
                .setSubject("system") // 说明
                .setIssuer("heima") // 签发者信息
                .setAudience("app") // 接收用户
                .compressWith(CompressionCodecs.GZIP) // 数据压缩方式
                .signWith(SignatureAlgorithm.HS512, TOKEN_ENCRY_KEY) // 加密方式
                .setExpiration(new Date(currentTime + EXPIRE_TIME)) // 过期时间戳
                .addClaims(claimMaps) // cla信息
                .compact();
    }

    /**
     * 获取payload body信息
     *
     * @param token
     * @return
     */
    public static Claims getClaimsBody(String token) {
        try {
            Jws<Claims> jwt = Jwts.parser().setSigningKey(TOKEN_ENCRY_KEY).parseClaimsJws(token);
            return jwt.getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取payload中claims的集合
     *
     * @param token
     * @return
     */
    public static Map<String, Object> getClaimsMap(String token) {
        try {
            Jws<Claims> jwt = Jwts.parser().setSigningKey(TOKEN_ENCRY_KEY).parseClaimsJws(token);
            return jwt.getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取hearder body信息
     *
     * @param token
     * @return
     */
    public static JwsHeader getHeaderBody(String token) {
        Jws<Claims> jwt = Jwts.parser().setSigningKey(TOKEN_ENCRY_KEY).parseClaimsJws(token);
        return jwt.getHeader();
    }

    /**
     * 是否过期
     *
     * @param claims
     * @return 1：有效，0：无效
     */
    public static int verifyToken(Claims claims) {
        if (claims == null) {
            return 0;
        }
        // 当前时间在有效期范围内
        if(new Date().before(claims.getExpiration())){
            return 1;
        }
        return 0;
    }

    public void removeToken(TUser tUser){
        redisCacheUtil.deleteObject(Constants.LOGIN_USER_KEY +tUser.getUserId());
    }
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", "1");
        map.put("userName", "狗剩");
        map.put("authorities", Arrays.asList("student:add","user:list"));

        String token = createToken(map);

        Map<String, Object> claimsMap = getClaimsMap(token);

        LinkedHashMap obj = (LinkedHashMap) claimsMap.get("user");

        String username = (String) obj.get("username");
        System.out.println(username);
        System.out.println(obj);
    }
    public void refreshToken(TUser user, Integer time, TimeUnit unit){
        redisCacheUtil.setCacheObject(Constants.LOGIN_USER_KEY + user.getUserId(), user, time, unit);
    }
}
